/*
 * @Author: xiaosihan 
 * @Date: 2023-09-09 00:50:58 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-09-24 19:11:57
 */



import designEditor from "@/editorComponent/designEditor";
import editorStore from "@/editorComponent/editorStore";
import { autorun } from "mobx";
import { useEffect, useRef, useState } from "react";
import styles from "./layer.module.less";
import FabricImage from "@/myFabric/FabricImage";
import FabricText from "@/myFabric/FabricText";
import textIconPNG from "./textIcon.png?url";
import utils from "@/utils/utils";
import clsx from "clsx";
import visibleSVG from "./visible.svg?raw";
import hideSVG from "./hide.svg?raw";
import lockSVG from "./lock.svg?raw";
import unlockSVG from "./unlock.svg?raw";
import ReactDragListView from "react-drag-listview";
import designDataHistory from "@/editorComponent/designDataHistory";
import { Popconfirm, Tooltip } from "antd";
import delSVG from "./del.svg?raw";


type LayerItem = { id: string, src: string, name: string, lock: boolean, visible: boolean };

// 图层
export default function Layer() {

  const dom = useRef<HTMLDivElement | null>(null);
  const [data, setData] = useState({});
  const [disable, setDisable] = useState(false);

  const [layerList, setLayerList] = useState<Array<LayerItem>>([]);
  const [activeObjectId, setActiveObjectId] = useState(editorStore.activeObjectId);

  useEffect(() => {

  }, []);

  useEffect(() => autorun(() => {
    setActiveObjectId(editorStore.activeObjectId);
    setDisable(editorStore.lock);
  }), []);

  useEffect(() => autorun(() => {
    const { layerIds } = editorStore;
    // 数据发生改变时 更新图层
    if (layerIds) {
      const objects = designEditor.fabricCanvas.getObjects();
      const layerList: Array<LayerItem> = [];

      objects.map(o => {
        if (o.type === "image") {
          layerList.unshift({
            id: (o as FabricImage).id,
            name: o.name || "--",
            src: utils.ossSuffix((o as FabricImage).getSrc(), 16),
            lock: designEditor.getLock((o as FabricImage).id),
            visible: !!o.visible
          });
        } else if (o.type === "i-text") {
          layerList.unshift({
            id: (o as FabricImage).id,
            src: textIconPNG,
            name: (o as FabricText).text,
            lock: designEditor.getLock((o as FabricImage).id),
            visible: !!o.visible
          });
        }
      });

      setLayerList(layerList);
    } else {
      setLayerList([]);
    }
  }), []);

  return (
    <ReactDragListView
      // 拖拽完成设置对象的位置
      onDragEnd={(fromIndex: number, toIndex: number) => {
        if (toIndex > -1) {
          const objects = designEditor.fabricCanvas.getObjects();
          const object = objects[(layerList.length - 1) - fromIndex];
          if (object) {
            object.moveTo((layerList.length - 1) - toIndex);
            designDataHistory.recordHistory();
          }
        }
      }}
      nodeSelector="li"
      handleSelector="span"
    >
      <ul
        className={styles.layer}
        onClick={(e) => {
          designEditor.setActiveById("");
        }}
      >
        {
          layerList.map((layerItem, i) => {
            return (
              <li
                key={layerItem.id}
                className={clsx(layerItem.id === activeObjectId && styles.active, styles.layer_item)}
                onClick={(e) => {
                  e.stopPropagation();
                  e.preventDefault();
                  designEditor.setActiveById(layerItem.id);
                }}
              >
                <img src={layerItem.src} alt="" className={styles.icon} />
                <span className={clsx(styles.name, "handle")} >{layerItem.name}</span>

                {/* 锁定状态图标 */}
                <span
                  className={clsx(styles.lock, layerItem.lock && styles.red)}
                  dangerouslySetInnerHTML={{ __html: layerItem.lock ? lockSVG : unlockSVG }}
                  onClick={() => {
                    designEditor.setLockById(layerItem.id, !layerItem.lock);
                  }}
                ></span>

                {/* 可见状态图标 */}
                <span
                  className={styles.visible}
                  dangerouslySetInnerHTML={{ __html: layerItem.visible ? visibleSVG : hideSVG }}
                  onClick={() => {
                    designEditor.setVisibleById(layerItem.id, !layerItem.visible);
                  }}
                ></span>

                {/* 删除 */}
                <Tooltip
                  title="删除(del)"
                  placement="bottom"
                  mouseLeaveDelay={0}
                  mouseEnterDelay={0.5}
                >
                  <Popconfirm
                    title="确定要删除当前组?"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => {
                      designEditor.delActiveObject();
                    }}
                  >
                    <span
                      className={clsx(styles.btn, disable && styles.disable)}
                      dangerouslySetInnerHTML={{ __html: delSVG }}
                    >
                    </span>
                  </Popconfirm>
                </Tooltip>

              </li>
            );
          })
        }
      </ul >
      {layerList.length === 0 && <div className={styles.no_object} >--没有元素--</div>}
    </ReactDragListView>
  );

}